#include "service_registry.h"
#include <chrono>
#include <iostream>

namespace cpp_backend {
namespace framework {

bool ServiceRegistry::register_service(const ServiceInstance& instance) {
    std::lock_guard<std::mutex> lock(registry_mutex_);
    
    database::RedisConnectionGuard conn(*redis_pool_);
    if (!conn.IsValid()) {
        std::cerr << "Failed to get Redis connection" << std::endl;
        return false;
    }
    
    try {
        // 1. 注册实例到Hash
        std::string instance_key = make_instance_key(instance.service_name);
        std::string instance_json = instance.to_json();
        
        if (!conn->HSet(instance_key, instance.instance_id, instance_json)) {
            std::cerr << "Failed to register service instance" << std::endl;
            return false;
        }
        
        // 2. 设置心跳（30秒TTL）
        std::string heartbeat_key = make_heartbeat_key(instance.instance_id);
        if (!conn->Set(heartbeat_key, "alive", 30)) {
            std::cerr << "Failed to set heartbeat" << std::endl;
            return false;
        }
        
        std::cout << "✓ Service registered: " << instance.service_name 
                  << " [" << instance.instance_id << "]" << std::endl;
        return true;
        
    } catch (const std::exception& e) {
        std::cerr << "Exception in register_service: " << e.what() << std::endl;
        return false;
    }
}

bool ServiceRegistry::unregister_service(const std::string& instance_id) {
    std::lock_guard<std::mutex> lock(registry_mutex_);
    
    database::RedisConnectionGuard conn(*redis_pool_);
    if (!conn.IsValid()) {
        return false;
    }
    
    try {
        // 删除心跳
        std::string heartbeat_key = make_heartbeat_key(instance_id);
        conn->Del(heartbeat_key);
        
        std::cout << "✓ Service unregistered: " << instance_id << std::endl;
        return true;
        
    } catch (const std::exception& e) {
        std::cerr << "Exception in unregister_service: " << e.what() << std::endl;
        return false;
    }
}

std::vector<ServiceInstance> ServiceRegistry::discover(const std::string& service_name) {
    std::vector<ServiceInstance> instances;
    
    database::RedisConnectionGuard conn(*redis_pool_);
    if (!conn.IsValid()) {
        return instances;
    }
    
    try {
        // 简化实现：暂时返回空列表
        // TODO: 实现HGETALL和解析逻辑
        std::cout << "[ServiceRegistry] discover() - simplified implementation" << std::endl;
        return instances;
        
    } catch (const std::exception& e) {
        std::cerr << "Exception in discover: " << e.what() << std::endl;
        return instances;
    }
}

bool ServiceRegistry::heartbeat(const std::string& instance_id) {
    database::RedisConnectionGuard conn(*redis_pool_);
    if (!conn.IsValid()) {
        return false;
    }
    
    try {
        std::string heartbeat_key = make_heartbeat_key(instance_id);
        return conn->Set(heartbeat_key, "alive", 30);
        
    } catch (const std::exception& e) {
        std::cerr << "Exception in heartbeat: " << e.what() << std::endl;
        return false;
    }
}

void ServiceRegistry::health_check() {
    // 健康检查由心跳TTL自动实现
    // 这里可以添加额外的清理逻辑
    std::cout << "Health check completed" << std::endl;
}

} // namespace framework
} // namespace cpp_backend
